package rubymatic;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.proxy.map.MapLazyInitializer;
import org.hibernate.proxy.map.MapProxy;
import org.hibernate.proxy.ProxyFactory;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.type.AbstractComponentType;
import org.jruby.Ruby;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.javasupport.JavaUtil;
import org.jruby.runtime.Block;
import org.jruby.runtime.builtin.IRubyObject;


public class RubyProxyFactory implements ProxyFactory
{

	private String entityName;

	public void postInstantiate(
		final String entityName,
		final Class persistentClass,
		final Set interfaces,
		final Method getIdentifierMethod,
		final Method setIdentifierMethod,
		AbstractComponentType componentIdType) 
	throws HibernateException
	{

		this.entityName = entityName;

	}

	public HibernateProxy getProxy(
		final Serializable id,
		final SessionImplementor session)
	throws HibernateException
	{
		Ruby runtime = ActiveHibernateUtil.getRubyInstance();
		
		RubyProxy rubyObject
			=  (RubyProxy)runtime.getModule("ActiveHibernate").getClass("RubyProxy").newInstance(
					new IRubyObject[0], Block.NULL_BLOCK);
		
		rubyObject.setHibernateLazyInitializer(new RubyLazyInitializer(entityName, id, session));
		
		return rubyObject;
		//return (HibernateProxy)JavaEmbedUtils.rubyToJava(runtime,rubyObject, HibernateProxy.class);
		//return new RubyProxy(new RubyLazyInitializer(entityName, id, session));
	}

}